<?php

/**
 * 用户
 * Author: zgs
 * Date: 1/26/18
 * Time: 15:25
 */

namespace Bojin\Model;
use Common\Library\BusinessException;
//use function PHPSTORM_META\elementType;
use Think\Log;
use Think\Model;
use Common\Library\Constant;
use Common\Library\CacheRedis;
use Bojin\Logic\UserLogic;

class CustomerModel extends Model
{
    const SEARCH_TYPE_REVIEWED = 0; //审批
    const SEARCH_TYPE_MOD_LOCATION = 1; //修改本地人
    const SEARCH_TYPE_ASSURE = 2; //担保
    const SEARCH_TYPE_UPLOAD = 3; //上传资料
    const STATUS_OK = 1; //正常用户

    public function has($data, $throwException = true) {
        if (is_numeric($data)) {
            $table_name = get_customer_table_by_id($data);
            $data = ['id' => $data];
        }else{
            $table_name = get_customer_table_by_id($data['id']);
        }
        if (!is_array($data)) {
            if ($throwException) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            return null;
        }

        //$data['status'] = array('eq',Constant::CUSTOMER_USE);
        $information = M($table_name)->where($data)->find();

        if (!$information) {
            $throwException && BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
        } else {
            $information['max_amount'] = Constant::MAX_CREDIT_AMOUNT;
            $information['isset_pay_pass'] = !empty($information['pay_pass']);
            unset($information['password'], $information['pay_pass']);
        }

        return $information;
    }
    
    public function addChannelCustomerRel($customer_id, $data)
    {
        //ignore
        $sql = 'insert ignore  into fb_customer (id, channel_id, ctime,device_id,add_time,update_time) values ('.
            $customer_id.', "'.$data['channel_id'].'","'.time().'","'.$data['device_id'].'",'.time().','.time().')';
        Log::write($sql, Log::DEBUG);
        $info = M()->execute($sql);//用户激活记录表

        return true;
    }
    /**
     * 校验手机号是否注册过    ----  弃用
     */
    public function chkCustomerByMobile($mobile)
    {   
        
        $user_logic = new UserLogic();
        $chkCustomerMobile = $user_logic->findUserIDForMobile($mobile);
        return $chkCustomerMobile;
    }
    
    // 根据用手机号获取 userID
    public function getUserIDForMobile($mobile){
        $user_logic = new UserLogic();
        $chkCustomerMobile = $user_logic->findUserIDForMobile($mobile);
        return $chkCustomerMobile;
    }
    // 根据userid 获取手机号
    public function getMobileForUserID($userid){
        $user_logic = new UserLogic();
        $chkCustomerMobile = $user_logic->findMobileForUserID($userid);
        return $chkCustomerMobile;
    }
//    根据用户id 获取手机号
    public function getMobileForCustomerID($customer_id){
        $customer_info = M('customer')->where(['id' => $customer_id])->getField("user_id");
        if (!empty($customer_info)) { // 有用户
            $user_logic = new UserLogic();
            $chkCustomerMobile = $user_logic->findMobileForUserID($customer_info);
            return $chkCustomerMobile;
        }else{
            return false;
        }
        
    }
    // 获取用户信息 根据userid
    public function getUserInfoForUserID($user_id){
        if( !$user_id ){
            return false;
        }
        $customer_info = M('customer')->where(['user_id' => $user_id])->find();
        if (!empty($customer_info)) { // 有用户
            return $customer_info;
        }else{
            return false;
        }  
    }
    // 获取用户信息 根据手机号 

    public function getUserInfoForMobile($mobile){
        $user_logic = new UserLogic();
        $chkCustomerMobile = $user_logic->findUserIDForMobile($mobile);
        if($chkCustomerMobile){
            $customer_info = $this->getUserInfoForUserID($chkCustomerMobile);
            if (!empty($customer_info)) { // 有用户
                return $customer_info;
            }else{
                return false;
            }  
        } else {
            return false;
        }
    }

    /**
     * 获取人脸识别状态
     */
    
    //   获取用户 认证支付状态  当前月份
    public function getUserPayStatus($customer_id){
        $recharge_time = M("Recharge")->field('pay_time')->where("pay_status = 1 and status = 1 and is_del = 0 and order_type = 1 and customer_id=".$customer_id)->order('pay_time desc')->find();
        if($recharge_time){
            $status = '1';
        }else{
            $status = '0';
        }
        return $status;
    }
    
    //   获取用户 出借人服务费支付状态  当前服务年
    public function getUserLenderPayStatus($customer_id){
        $recharge_time = M("Recharge")->field('pay_time')->where("pay_status = 1 and status = 1 and is_del = 0 and order_type = 2 and customer_id=".$customer_id)->order('pay_time desc')->find();
//        $recharge_time = $recharge_time['pay_time']+30*24*60*60*365;
        if( $recharge_time ){
            $status = 1;
        }else{
            $status = 0;
        }
        return $status;
    }
    //   获取用户额度
    public function getUserCreditMoney($customer_id){
        $credit_money = $this->where("is_del = 0 and id=".$customer_id)->getField("credit_money");
        if(!empty($credit_money)){
            return true;
        }
        return false;
    }
    //获取用户身份证居住地址并处理
    public function getLoginAddress( $customer_id ){
        $address = "";
        $customerDetail = $this->where("id=".$customer_id)->getField("birthplace");
        if( $customerDetail ){
            $address = $this->getBirthplace($customerDetail);
        }
        return $address;
    }
    public function getBirthplace($birthplace){
        $xian_address = strstr($birthplace,"县",true);
        if( !$xian_address ){
            $xian_address = $birthplace;
        }
        $shi_address = strstr($xian_address,"市",true);
        if( !$shi_address ){
            return $xian_address."县";
        }
        $sheng_address = strstr($shi_address,"省",false);
        if( $sheng_address ){
            $address = substr($sheng_address,3);
            $address = $address."市";
        }else{
            $address = $shi_address;
        }
        return $address;
    }
    //获取用户信息
    public function getUserDetail($customer_id,$type=1){
        if( !$customer_id ){
            return false;
        }
        $API_SERVER_HOST = C("API_SERVER_HOST");
        if( $type == 1 ){
            $gender = $this->where("is_del = 0 and id=".$customer_id)->getField("gender");

            $data['headerImg'] = $API_SERVER_HOST."/Public/images/UserImg/default.png";
            if( $gender == "男" ){
                $data['headerImg'] = $API_SERVER_HOST."/Public/images/UserImg/boy.png";
            }
            if( $gender == "女" ){
                $data['headerImg'] = $API_SERVER_HOST."/Public/images/UserImg/girl.png";
            }
            $res = $this->field("id,invite_code")->where("id = $customer_id")->find();
            $data['count'] = $this->where("inviter_code = '".$res['invite_code']."'")->count();
            return $data;
        }else{
            $detail = $this->field("id,real_name,id_num,is_lenders,birthplace,add_time,award_balance,invite_code,user_id,recharge_amount,balance")->where("is_del = 0 and id=".$customer_id)->find();

            $detail['count'] = $this->where("inviter_code = '".$detail['invite_code']."'")->count();

            if( !$detail ){
                $detail = array();
            }
            return $detail;
        }
    }
    //   获取用户是否交过查看自己信用报告的费用
    public function getUserSelfPayStatus($customer_id){
        if( !$customer_id ){
            return 0;
        }
        $recharge_time = M("Recharge")->field('id')->where("pay_status = 1 and status = 1 and is_del = 0 and order_type = 3 and check_person=".$customer_id." and be_viewed_person=".$customer_id)->order('pay_time desc')->find();
        if($recharge_time){
            $status = '1';
        }else{
            $status = '0';
        }
        return $status;
    }
    //获取用户是否交过服务费
    public function getUserServicePayStatus($customer_id){
        if( !$customer_id ){
            return 0;
        }
        $recharge_time = M("Recharge")->field('id')->where("pay_status = 1 and status = 1 and is_del = 0 and order_type = 1 and customer_id=".$customer_id)->order('pay_time desc')->find();
        if($recharge_time){
            $status = '1';
        }else{
            $status = '0';
        }
        return $status;
    }
    /*
     * 邀请的人添加奖励金豆
     * $customer_id 被邀请人ID
     */
    public function addUserAwardBalance($customer_id){
        $inviteeDetail = $this->field("invite_code,inviter_code,award_balance,is_lenders")->where("id=".$customer_id)->find();
        $inviterDetail = $this->field("id,is_lenders")->where("invite_code='".$inviteeDetail['inviter_code']."'")->find();
        if( !$inviteeDetail['inviter_code'] ){
            return true;
        }

        $money = D("Invite")->getRewardNum($customer_id);
        if( $money > 0 ){
            $order_number = getOrderNumber(1);
            $data = array(
                "customer_id"=>$inviterDetail['id'],
                "order_number"=>$order_number,
                "order_type"=>8,
                "pay_money"=>$money,
                "pay_type"=>4,
                "pay_category"=>1,
                "money_type"=>1,
                "pay_status"=>1,
                "invite_code"=>$inviteeDetail['inviter_code'],
                "be_invited_id"=>$customer_id,
                "pay_time"=>time(),
                "ctime"=>time(),
                "utime"=>time(),
                "add_time"=>time()
            );
            $recharge = M("Recharge");
            $res = $recharge->add($data);
            if( $res ){
                $ret = $this->where('id='.$inviterDetail['id'])->setInc('award_balance',$money);
                if( !$ret ){
                    Log::write("给用户充值邀请额度失败 sql: " .$this->_sql(). "\r\n", Log::DEBUG);
                }
            }else{
                Log::write("消费表：给用户增加充值邀请额度记录失败 sql: " .$recharge->_sql(). "\r\n", Log::DEBUG);
            }
        }
    }
    //  获取用户本平台黑名单状态
    public function getBlickStatus($id_num){
        $blick = M("Blacklist")->where("id_num = '".$id_num."'")->find();
        
        if($blick){
            return 1;
        }else{
            return 0;
        }
    }
    
//    获取用户本平台逾期状态
    public function getOverdueStatus($customer_id){
        $iou = M('Iou')->where('borrow_person_id = '.$customer_id.' and status in(1,3)')->select();
        if($iou){
            $time = strtotime(date("Y-m-d",time()));
            foreach ($iou as $key => $value) {
                if( $value['borrow_end_time'] < $time){
                    return 1;
                    break;
                }
            }
        }else{
            return 0;
        }
    }

    // 判断邀请码是否正确
    public function checkInviteCode( $invite_code ){
        if( !$invite_code ){
            return false;
        }
        $invite_code = $this->where("is_del = 0 and invite_code='".$invite_code."'")->find();
        if( $invite_code ){
            return true;
        }else{
            return false;
        }
    }

    //提现--列表
    public function withdrawData( $customer_id ){
        $data = array();
        if( !$customer_id ){
            return $data;
        }
        $serviceFee = 0;
        $Recharge = D("Recharge");
        $customerDetail = $this->getUserDetail($customer_id,2);
        $data['balance'] = ($customerDetail['balance']/100);
        $data['rechargeAmount'] = ($customerDetail['recharge_amount']/100);
        $isServiceFee = $Recharge->serviceFee($customer_id);
        if( $isServiceFee ){
            $serviceFee = $Recharge->getserviceFee($customer_id);
        }
        $data['serviceFee'] = $serviceFee/100;
        return $data;
    }



    //领取完额度修改用户状态（李雅倩）
    public function receiveQuotaStatus($customer_id){
        $customer = M('customer');
        $res = $customer->field("id")->where("id = {$customer_id}")->find();
        if($res){
            $customer->is_lenders = 0;
            $result = $customer->where("id = '".$res['id']."'")->save();
            if($result){
                return true;
            }
            return false;
        }
        return false;
    }

    //获取用户可用余额及充值额度(李雅倩)
    public function getUserQuota($customer_id){
        if(!$customer_id){
            return false;
        }
        $customer = $this->field("balance,recharge_amount")->where("id = {$customer_id}")->find();
        if($customer){
            return $customer;
        }else{
            return false;
        }
    }
    //获取所用渠道
    public function channellist()
    {
        return $this->query("select channel_id from fb_customer where id in (select min(id) from fb_customer group by channel_id)");
    }
    //根据渠道编号获取渠道名称
    public function numbergetname($number)
    {
        $data=$this->query('select channel_name from fb_channel where channel_number = '."'$number'");
        return $data[0]['channel_name'];
    }
}